package com.myblog.myblog.service.impl;

import cn.hutool.core.util.IdUtil;
import com.myblog.myblog.domain.BOtherpage;
import com.myblog.myblog.domain.BOtherpageDetail;
import com.myblog.myblog.mapper.BOtherpageDetailMapper;
import com.myblog.myblog.mapper.BOtherpageMapper;
import com.myblog.myblog.service.OtherPageService;
import com.myblog.myblog.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author gyl
 * @data 2019/12/15 22:44
 */
@Service
public class OtherPageServiceImpl implements OtherPageService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    BOtherpageMapper bOtherpageMapper;

    @Autowired
    BOtherpageDetailMapper bOtherpageDetailMapper;

    @Autowired
    RedisUtil redisUtil;



    @Override
    public List selectAll() {
        List<BOtherpage> otherpage;
        boolean Otherpage_all = redisUtil.hasKey("Otherpage_all");
        if(Otherpage_all){
            otherpage = (List)redisUtil.get("Otherpage_all");
            System.out.println("-----"+otherpage.get(0));
            System.out.println("***"+otherpage);
            return otherpage;
        }
        otherpage = bOtherpageMapper.selectAll();
        redisUtil.set("Otherpage_all", otherpage);
        return otherpage;
    }

    @Override
    public boolean insertOtherPage(BOtherpage bOtherpage){
        BOtherpage bOtherpageNew = bOtherpageMapper.selectByBOtherpage(bOtherpage);
        String id = null;
        if(bOtherpageNew != null){
            bOtherpageNew.setOtherpageCount((Integer.valueOf(bOtherpageNew.getOtherpageCount())+1)+"");
            bOtherpageMapper.updateByPrimaryKeySelective(bOtherpageNew);
        } else {
            id = IdUtil.simpleUUID();
            bOtherpage.setId(id);
            bOtherpage.setOtherpageCount("0");
            bOtherpageMapper.insert(bOtherpage);
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 日期时间转字符串
        LocalDateTime now = LocalDateTime.now();
        String nowText = now.format(formatter);
        BOtherpageDetail bOtherpageDetail = new BOtherpageDetail();
        bOtherpageDetail.setId(IdUtil.simpleUUID());
        bOtherpageDetail.setOtherpageId(id == null? bOtherpageNew.getId():id);
        bOtherpageDetail.setOpenDate(nowText);
        bOtherpageDetailMapper.insert(bOtherpageDetail);

        //添加后清除缓存
        redisUtil.del("Otherpage_all");

        return true;
    }
}